package com.lovo.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lovo.config.ApplicationConfig;
import com.lovo.model.UserDO;
import com.lovo.service.UserService;
import com.lovo.service.impl.UserServiceImpl;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @title
 * @author: luo
 * @date: 2020/11/17 12:42
 */
@Component
@WebServlet(name = "userServlet",urlPatterns = "/findUser")
public class UserServlet extends HttpServlet {
    @Resource
    private  UserService userService;

    @Override
    public void init() throws ServletException {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class);
        userService = context.getBean(UserServiceImpl.class);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        String id = req.getParameter("userId");
        Integer userId = Integer.parseInt(id);
        System.out.println(userId);
        UserDO userDO = userService.findById(userId);
        ObjectMapper mapper = new ObjectMapper();
        resp.getWriter().print(mapper.writeValueAsString(userDO));

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
